package cs236369.hw5;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet({"/UpdateTask", "/UpdateTask/*"})
public class UpdateTask extends HttpServlet {
	private static final long serialVersionUID = 8012589024487063645L;
	private HttpSession session;
	private PrintWriter out;
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession();
		try {
			out = response.getWriter();
		} catch (IOException e) {
			response.setStatus(400);
			return;
		}
		// if no session- redirect to welcome page
		if(session == null || session.getAttribute("userName") == null) {
			response.sendRedirect(request.getContextPath() + InitListener.welcomePage);
			return;
		}			
		
		try {
			String command = request.getParameter("command");
			if(command == null) {
				updateTask(request);
			} else if(command.equals("delete")) {
				deleteTask(request);
			} else if(command.equals("match task")) {
				matchTask(request);
			} else if(command.equals("match team")) {
				matchTeam(request);
			} else {
				System.err.println("Command " + command + " is unknown");
				throw new RescueMeException("unknown command", "Command " + command + " is unknown");
			}
			response.setStatus(200);
			out.print("Task updated successfully");
		} catch (RescueMeException e) {
			response.setStatus(400);
			out.print(e.getMessage());
		}
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private void updateTask(HttpServletRequest request) throws RescueMeException {
		// create skills array
		ArrayList<Skill> skills = new ArrayList<Skill>();	// to add skills dynamically
		Skill[] sa = new Skill[0];	// a dummy array for creating skills arrays
		Map<String, String[]> params = request.getParameterMap();
		for (String parameter : params.keySet()) {
		    if(parameter.contains("newSkillId")) {
		    	try {
			    	int skillID = Integer.parseInt(params.get(parameter)[0]);
			    	if(skillID > -1 ) { skills.add(new Skill(skillID, "", true)); }
		    	} catch (NumberFormatException e) {
		    		throw new RescueMeException("illegal parameter", "Skill ID is incorrect");
				} 
		    }
		}
		
		String numberString = request.getParameter("capacity");
		int capacity;
		try {
			if(numberString == null || Integer.parseInt(numberString) < 0) {
				throw new RescueMeException("illegal parameter", "Capacity is not a positive integer");
			} else {
				capacity = Integer.parseInt(numberString);
			}
		} catch (NumberFormatException e) {
			throw new RescueMeException("illegal parameter", "Capacity is not a positive integer");
		}
		Mission m = new Mission(getTaskId(request), (String)session.getAttribute("userName"), 
				null, null, capacity, request.getParameter("content"), 0, 0, skills.toArray(sa));
		DBConnection.updateMission(m);
	}
	
	private void deleteTask(HttpServletRequest request) throws RescueMeException {
		int taskId = getTaskId(request);
		Mission task = DBConnection.getMission(taskId);
		if(!task.getOwner().equals(session.getAttribute("userName"))) {
			throw new RescueMeException("unauthorized", "This user is unauthorized to delete task id " + taskId);
		}
		DBConnection.delPost(taskId, 0);
	}
	
	private void matchTask(HttpServletRequest request) throws RescueMeException {
		Mission task = DBConnection.getMission(getTaskId(request));
		session.setAttribute("matchingTaskId", task.getId());
		session.setAttribute("matchingTaskName", task.getName());
		match();
	}
	
	private void matchTeam(HttpServletRequest request) throws RescueMeException {
		Team team = DBConnection.getTeam(updateTeam.getTeamId(request));
		session.setAttribute("matchingTeamId", team.getId());
		session.setAttribute("matchingTeamName", team.getName());
		match();
	}
	
	private void match() throws RescueMeException {
		Integer matchingTaskId = (Integer) session.getAttribute("matchingTaskId");
		Integer matchingTeamId = (Integer) session.getAttribute("matchingTeamId");
		if(matchingTaskId != null && matchingTeamId != null) {
			DBConnection.matchTeamToMission(matchingTeamId, matchingTaskId);
			session.removeAttribute("matchingTaskId");
			session.removeAttribute("matchingTeamId");
			session.removeAttribute("matchingTeamName");
			session.removeAttribute("matchingTaskName");
		}
	}
	
	private int getTaskId(HttpServletRequest request) throws RescueMeException {
		String numberString = request.getParameter("taskId");
		try { return Integer.parseInt(numberString); }
		catch (NumberFormatException e) {
			throw new RescueMeException("illegal parameter", "Task id is incorrect");
		}
	}
}
